import axios, { AxiosRequestConfig } from "axios";
import { message } from "antd";
import Router from "@/bootstrap/router";
import { useNavigate } from "react-router-dom";
const http = axios.create({
    baseURL: '/api',
    timeout: 3000,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8'
    }
})
axios.defaults.withCredentials = false;

let urlList = new Set();

function setUrl(url: string = '') {
    if (url) urlList.add(url);
}

function resetUrl() {
    urlList = new Set();
}

function Authorization(config: AxiosRequestConfig) {
    const authorization = localStorage.getItem("Authorization");
    if (!authorization) return;
    config.headers = {
        ...config.headers
    }
    config.headers['Authorization'] = `Bearer ${authorization}`;
}

http.interceptors.request.use(config => {
    // Authorization(config);
    if (urlList.has(config.url)) return Promise.reject();
    setUrl(config.url);
    const authorization = localStorage.getItem("Authorization");
    if(config.headers) config.headers['Authorization'] = `Bearer ${authorization}`;
    return config;
}, error => {
    resetUrl();
    return Promise.reject(error)
})

http.interceptors.response.use(res => {
    resetUrl();
    return Promise.resolve(res.data.data);
}, err => {
    try {
        resetUrl();
        return Promise.reject(err);
        const { message, status } = err.response.data;
        if (!JSON.stringify(err).includes('timeout of')) return Promise.reject(responseError(status, message));
        const config = err.config;
        if (!config || !config.retry) return Promise.reject(err);
        config.retryCount = config.retryCount || 0;
        if (config.retryCount >= 5) return Promise.reject(err);
        config.retryCount += 1;
        const backoff = new Promise<void>((resolve): any => setTimeout(() => resolve(), config.retryDelay || 1));
        return backoff.then(() => http(config));
    } catch {
        return Promise.reject(err);
    }
})

function responseError(status: number, msg: string) {
    try {
        const formatMessage = (status: number) => ({
            '401': '无权限，请登录',
            '403': '权限不足,禁止访问',
            '500': msg || '服务器响应失败',
        })[status] || '网络请求错误，请重试';
        message.error(formatMessage(status))
        if (status == 401) {
            Router.navigate('/login');
            window.location.reload();
        }
    } catch (e) {
        console.log('on Error is Null');
    }
}

export function get(api: string, params: any = null): Promise<any> {
    return http.get(api, params);
}

export function post(api: string, data: any = null): Promise<any> {
    return http.post(api, data);
}

export function put(api: string, data: any = null): Promise<any> {
    return http.put(api, data);
}

export function deletes(api: string): Promise<void> {
    return http.delete(api);
}

export function upload(api: string, data: any): any {
    let formData = new FormData();
    formData.append('file', data);
    return http.post(api, formData,
        {
            headers: { 'Content-Type': 'multipart/form-data' }
        });
}

export default {
    get,
    post,
    put,
    deletes,
    upload
};
